package com.yuntoyun.fwcore.plug.tool;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

public class FwTool {

    private static final String TAG = "FwTool";

    private static FwTool init = null;

    public static synchronized FwTool builder() {
        if (null == init) {
            init = new FwTool();
        }
        return init;
    }

    public String getClickText(View clickableSpanOnclickWidget) {
        if (null == clickableSpanOnclickWidget) {
            return "";
        }
        TextView tvw = (TextView) clickableSpanOnclickWidget;
        return tvw.getText().subSequence(tvw.getSelectionStart(), tvw.getSelectionEnd()).toString().trim();
    }

    public void setClickText(TextView tvwView, String strText, String clickText[], ClickableSpan clickSpan[]) {
        SpannableStringBuilder ssb = new SpannableStringBuilder(strText);
        if (clickText.length <= clickSpan.length) {
            for (int i = 0; i < clickText.length; i++) {
                int beginIndex = strText.indexOf(clickText[i]);
                int endIndex = beginIndex + clickText[i].length();
                ssb.setSpan(clickSpan[i], beginIndex, endIndex, 0);
            }
            tvwView.setMovementMethod(LinkMovementMethod.getInstance());
            tvwView.setText(ssb, TextView.BufferType.SPANNABLE);
        }
    }

    public void setClipboardText(FragmentActivity activity, String text) {
        ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(text, text);
        cm.setPrimaryClip(clipData);
    }

    public String getClipboardText(FragmentActivity activity) {
        ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        //判断剪切版时候有内容
        if (!cm.hasPrimaryClip())
            return "";
        ClipData clipData = cm.getPrimaryClip();
        return clipData.getItemAt(0).getText().toString();
    }

}
